import React, {Component} from 'react';
import css from './index.css';
/*
* 用一个长度为9的数组存储井字棋的所有方格，初始值都为null，选中时为X或O
* */

//游戏面板组件，为当前组件的最上层
class Game extends Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{squares: Array(9).fill(null)}],//记录方格的历史状态，默认开局每个方格的内容都为null
      xIsNext: true,//判断下一个玩家是X还是O
      stepNumber: 0//当前步骤编号
    };
  }

  /**
   * 计算玩家是否胜利
   * @param squares
   */
  calculateWinner(squares) {
    const lines = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6]
    ];
    for (let i = 0; i < lines.length; i++) {
      const [a, b, c] = lines[i];
      //判断胜利状态中三个方格是否为同一种值，若相同则返回当前胜利者
      if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
        return squares[a];
      }
    }
    return null;
  }

  /**
   * 在Game层组件定义的方法，按顺序Game》Board》Square依次传递，当button触发该方法时，改变Game层的state
   * @param i
   */
  handleClick(i) {
    //截取从0到当前步骤的游戏历史记录，以创建副本的形式获取数组，保持state值的不可变性
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    //获取当前游戏状态
    const current = history[history.length - 1];
    //当前方格状态
    const squares = current.squares.slice();
    //判断游戏是否出现胜利玩家
    const winner = this.calculateWinner(squares);
    //出现胜利者或方格已经已选择(有值)，直接返回
    if (winner && squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat({squares: squares}),
      xIsNext: !this.state.xIsNext,
      stepNumber: history.length
    });
  }

  //
  jumpTo(step) {
    this.setState({xIsNext: (step % 2) === 0, stepNumber: step});
  }

  render() {
    const history = this.state.history;
    //获取当前游戏状态
    const current = history[this.state.stepNumber];
    //当前方格状态
    const squares = current.squares;
    //判断游戏是否出现胜利玩家
    const winner = this.calculateWinner(squares);
    //创建游戏记录列表
    const moves = history.map((item, step) => {
      const desc = step ? ('到步骤#' + step) : '游戏开始';
      return (
          <li key={step}>
            <button onClick={() => {
              this.jumpTo(step);
            }}>{desc}</button>
          </li>);
    });
    //游戏进行状态
    let status;
    //有胜利者
    if (winner) {
      status = '游戏结束!胜利者是' + winner;
    } else {
      status = '下一步轮到：' + (this.state.xIsNext ? 'X' : 'O');
    }
    return (
        <div className={css.game}>
          <div className={css['game-board']}>
            <Board onClick={(i) => {
              this.handleClick(i);
            }} squares={squares}/>
          </div>
          <div className={css['game-info']}>
            <div className={css.status}>{status}</div>
            <ol>{moves}</ol>
          </div>
        </div>);
  }
}

//所有方格组件
class Board extends Component {
  renderSquare(i) {
    return (
        <Square onClick={() => {
          this.props.onClick(i);
        }} value={this.props.squares[i]}/>
    );
  }

  render() {
    return (
        <div>
          <div className={css['board-row']}>
            {this.renderSquare(0)}
            {this.renderSquare(1)}
            {this.renderSquare(2)}
          </div>
          <div className={css['board-row']}>
            {this.renderSquare(3)}
            {this.renderSquare(4)}
            {this.renderSquare(5)}
          </div>
          <div className={css['board-row']}>
            {this.renderSquare(6)}
            {this.renderSquare(7)}
            {this.renderSquare(8)}
          </div>
        </div>
    );
  };
}

//单独小方格组件
function Square(props) {
  return (
      <button className={css.square} onClick={props.onClick}>
        {props.value}
      </button>
  );
}

export default Game;
